package rate

import (
	"fmt"
	"github.com/goccy/go-json"
	"lib/config"
	"lib/log"
	"net/http"
	"net/url"
	"strconv"
	"strings"
)

type GetCurrencyInfoListResp struct {
	ErrorCode  int                       `json:"error_code"`
	Resultcode string                    `json:"resultcode"`
	Reason     string                    `json:"reason"`
	Result     []map[string]CurrencyInfo `json:"result"`
}

type CurrencyInfo struct {
	BankConversionPri string `json:"bankConversionPri"`
	Date              string `json:"date"`
	FBuyPri           string `json:"fBuyPri"`
	FSellPri          string `json:"fSellPri"`
	MBuyPri           string `json:"mBuyPri"`
	MSellPri          string `json:"mSellPri"`
	Name              string `json:"name"`
	Time              string `json:"time"`
}

// 获取任人民币汇率
func getCnyRate() {
	// 基本参数配置
	apiUrl := "http://web.juhe.cn/finance/exchange/rmbquot"
	apiKey := config.GetSystemConfig().JuheRateKey
	if strings.EqualFold(apiKey, "") {
		apiKey = "d4dc495273925867d637fa108116afca"
	}

	// 接口请求入参配置
	requestParams := url.Values{}
	requestParams.Set("key", apiKey)
	requestParams.Set("type", strconv.Itoa(1))
	requestParams.Set("bank", "3")

	// 发起接口网络请求
	resp, err := http.Get(apiUrl + "?" + requestParams.Encode())
	if err != nil {
		log.Errorf("获取汇率失败: %v", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		log.Error(fmt.Sprintf("获取汇率失败: httpStatusCode %d", resp.StatusCode))
		return
	}

	var responseResult GetCurrencyInfoListResp
	err = json.NewDecoder(resp.Body).Decode(&responseResult)
	if err != nil {
		log.Error("获取汇率失败: 解析响应结果异常, " + err.Error())
		return
	}

	buf, err := json.Marshal(responseResult)
	if err != nil {
		log.Error("获取汇率失败: 解析响应结果异常, " + err.Error())
		return
	}

	log.Info("获取汇率返回信息：" + string(buf))

	if !strings.EqualFold(responseResult.Resultcode, "200") {
		log.Error(fmt.Sprintf("获取汇率失败: httpStatusCode %s %d %s", responseResult.Resultcode, responseResult.ErrorCode, responseResult.Reason))
		return
	}

	for _, currencyMap := range responseResult.Result {
		for _, currency := range currencyMap {
			globalCurrencyMap.setPreCurrencyRate(currency.Name, currency.BankConversionPri)
		}
	}
}
